package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"hc_server/routers/response/merchantResponse"
)

// MerchantRate 商户费率
type MerchantRate struct {
	Model
	ActivityId    int     `json:"activity_id" gorm:"comment:'活动政策id'"`
	MerchantId    int     `json:"merchant_id" gorm:"comment:'商户ID'"`
	AgentRelation string  `json:"agent_relation" gorm:"comment:'代理商关系'"`
	Type          int     `json:"type" gorm:"comment:'费率类型 0=D0 1=D1'"`
	Wechat        float64 `json:"wechat" gorm:"type:decimal(10,6);comment:'微信费率'"`
	Alipay        float64 `json:"alipay" gorm:"type:decimal(10,6);comment:'支付宝费率'"`
	YunPayMin     float64 `json:"yun_pay_min" gorm:"type:decimal(10,6);comment:'云闪付费率<=1000元'"`
	YunPayMax     float64 `json:"yun_pay_max" gorm:"type:decimal(10,6);comment:'云闪付费率>1000元'"`
	DebitCard     float64 `json:"debit_card" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡费率'"`
	DebitCardMax  float64 `json:"debit_card_max" gorm:"type:decimal(10,6);comment:'刷卡储蓄卡封顶手续费'"`
	CreditCard    float64 `json:"credit_card" gorm:"type:decimal(10,6);comment:'刷卡信用卡费率'"`
}

// MerchantRateExistByID 通过id判断是否存在
func MerchantRateExistByID(id int) (bool, error) {
	var mer MerchantRate
	err := db.Select("id").Where("id = ?", id).First(&mer).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此商户费率不存在: id:%d err:%v", id, err)
		return false, fmt.Errorf("此商户费率不存在")
	}

	return mer.ID > 0, nil
}

// MerchantRateInfoByMerchantId 通过MerchantId获取数据
func MerchantRateInfoByMerchantId(merchantId int) (*merchantResponse.GetMerchantRateInfoResponse, error) {
	var mer *merchantResponse.GetMerchantRateInfoResponse
	err := db.Model(&MerchantRate{MerchantId: merchantId}).First(&mer).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此商户费率不存在: id:%d err:%v", merchantId, err)
		return nil, fmt.Errorf("此商户费率不存在")
	}

	return mer, nil
}
